package com.itheima.reggie.controller;


import com.itheima.reggie.domain.User;
import com.itheima.reggie.dto.LoginDto;
import com.itheima.reggie.dto.LoginUserDto;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.vo.R;
import com.itheima.reggie.vo.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserService userService;

    /**
     * 发送验证码
     *
     * @param dto
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMSg(@RequestBody LoginUserDto dto) {
        //1.生成一个随机的验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);

        //2.调用短信接口发送短信
        System.out.println("发送的验证码为：" + code);

        //3.todo用户再登录的时候，还需要校验验证码
        HttpSession session = request.getSession();
        //todo key不能乱写，必须是手机号，否者出问题，获取验证码后，用户更改手机号还能登录
        session.setAttribute(dto.getPhone(), code);
        return R.success("验证码发送成功");
    }

    /**
     * 用户登录
     *
     * @param dto
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginDto dto) {
        if (dto == null) {
            return R.error("参数异常");
        }
        //1.todo 获取session中的验证码
        HttpSession session = request.getSession();
        String sessionCode = (String) session.getAttribute(dto.getPhone());
        //2.todo 校验验证码是否正确
        if (null == sessionCode || !dto.getCode().equals(sessionCode)) {
            return R.error("验证码错误");
        }
        //3.todo （验证码匹配）判断验证码是否是该用户
        User user = userService.findByPhone(dto.getPhone());
        if (user != null) {

            session.setAttribute("user", user);

            return R.success(user);
        }
        //4.todo 如果不存在，注册一个用户添加到数据库user中
        User user1 = new User();
        user1.setPhone(dto.getPhone());
        user1.setStatus(1);//账号状态
        userService.save(user1);

        session.setAttribute("user", user1);

        return R.success(user1);
    }

    /**
     * 用户退出
     */
    @PostMapping("/loginout")
    public R logout(HttpSession session) {
        //清理当前session
        session.invalidate();
        return R.success("退出成功");
    }
}
